package capstoneproject.dudiachi.Main;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import capstoneproject.dudiachi.Controller.FestivalManager;
import capstoneproject.dudiachi.Controller.IslandArticleManager;
import capstoneproject.dudiachi.Controller.OldDistrictManager;
import capstoneproject.dudiachi.Controller.PlaceManager;
import capstoneproject.dudiachi.Model.Festival;
import capstoneproject.dudiachi.Model.IslandArticle;
import capstoneproject.dudiachi.Model.OldDistrict;
import capstoneproject.dudiachi.Model.Place;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.BufferType;

public class DetailPlaceActivity extends BaseActivity{

	private TextView tag;
	private TextView content2;
	private TextView source;
	private TextView caption2;
	private ImageView image2;
	private TextView content1;
	private TextView caption1;
	private ImageView image1;
	private TextView name;
	private ArrayList<String> listPosKey, listKeyAndValue = new ArrayList<String>();
	private ArrayList<Integer> listb, listi, listPos;
	private ArrayList<String> listPosTag;
	private ArrayList<String> listTag;
	private String textSize;
	private String duration;
	private ArrayList<Place> diahinh;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		BaseActivity.POS = 2;
		setContentView(R.layout.activity_detail_place);
		
		name = (TextView) findViewById(R.id.name);
		image1 = (ImageView) findViewById(R.id.image1);
		caption1 = (TextView) findViewById(R.id.caption1);
		content1 = (TextView) findViewById(R.id.content1);
		image2 = (ImageView) findViewById(R.id.image2);
		caption2 = (TextView) findViewById(R.id.caption2);
		content2 = (TextView) findViewById(R.id.content2);
		source = (TextView) findViewById(R.id.source);
		tag = (TextView) findViewById(R.id.tag);
		
		Intent intent = getIntent();
		Bundle b = intent.getExtras();
		final String id = b.getString("id");
		
		String cont1 = "", cont2 = "";
		diahinh = (ArrayList<Place>) intent.getSerializableExtra("list");
		for (Place item : diahinh) {
			if (item.getPlaceID().equals(id)) {
				name.setText(item.getPlaceName());
				name.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(DetailPlaceActivity.this, GoogleMapActivity.class);
						Bundle b = new Bundle();
						b.putString("id", id);
						b.putString("tag", "fromPlace");
						intent.putExtras(b);
						startActivity(intent);
					}
				});
				source.setText(item.getSource());
				try {
					if (item.getImage1() != null) {
						image1.setImageBitmap(GetBitmapFromAsset.getBitmapFromAsset(this, "Images/DiaDanh/" + item
								.getImage1()));
						caption1.setText(item.getCaption1());
					}
					if (item.getImage2() != null) {
						image2.setImageBitmap(GetBitmapFromAsset.getBitmapFromAsset(this, "Images/DiaDanh/" + item
								.getImage2()));
						caption2.setText(item.getCaption2());
					}
				} catch (IOException e) {
					e.printStackTrace();
				}

				if (item.getPart1() != null) {
					cont1 = textEffect1(item.getPart1());
					textEffect2(content1, cont1, listKeyAndValue,
							listb, listi);
				} 

				if (item.getPart2() != null) {
					cont2 = textEffect1(item.getPart2());
					textEffect2(content2, cont2, listKeyAndValue,
							listb, listi);
				} 
				
				if (item.getTag() != null) {
					makeTag(tag, item.getTag());
				}
			}
		}
		SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
		textSize = sharedPref.getString(SettingFragment.CO_CHU, "");
		duration = sharedPref.getString(SettingFragment.THOI_GIAN_CHU_THICH, "");
		if(textSize.equals("1")){
			content1.setTextAppearance(getApplicationContext(), android.R.style.TextAppearance_Small);
			content2.setTextAppearance(getApplicationContext(), android.R.style.TextAppearance_Small);
		}
		if(textSize.equals("2")){
			content1.setTextAppearance(getApplicationContext(), android.R.style.TextAppearance_Medium);
			content2.setTextAppearance(getApplicationContext(), android.R.style.TextAppearance_Medium);
		}
		if(textSize.equals("3")){
			content1.setTextAppearance(getApplicationContext(), android.R.style.TextAppearance_Large);
			content2.setTextAppearance(getApplicationContext(), android.R.style.TextAppearance_Large);
		}
		content1.setTextColor(getResources().getColor(R.color.black));
		content2.setTextColor(getResources().getColor(R.color.black));
	}

	private String textEffect1(String myString) {

		listb = new ArrayList<Integer>();
		listi = new ArrayList<Integer>();
		listPos = new ArrayList<Integer>();

		StringBuilder strBuilder = new StringBuilder();
		char[] myStringCharArray = myString.toCharArray();
		String uncompletedString = "";
		String stringToCheck = "";
		int cutPoint = 0, count = 0;

		for (int a = 0; a < myStringCharArray.length; a++) {
			if (myStringCharArray[a] == '[') {
				listPos.add(a + 1);
			}
			if (myStringCharArray[a] == ']') {
				listPos.add(a);
			}
		}

		int i = 0;
		String key = "", value = "", sign = "";
		while (i < listPos.size()) {
			int i1 = listPos.get(i);
			int i2 = listPos.get(i + 1);

			stringToCheck = myString.substring(i1, i2);
			StringTokenizer token = new StringTokenizer(stringToCheck, "|");

			while (token.hasMoreTokens()) {
				if (token.countTokens() == 2) {
					key = token.nextToken();
					sign = "";
					value = token.nextToken();
				} else {
					key = token.nextToken();
					sign = token.nextToken();
					value = token.nextToken();
				}
			}

			listKeyAndValue.add(key + "-" + sign + "-" + value);

			i = i + 2;
		}

		listPos.clear();
		int flag = 0;
		for (int c = 0; c < myStringCharArray.length; c++) {
			flag = 0;
			if (myStringCharArray[c] == '<') {

				if (myStringCharArray[c + 1] == 'b') {
					strBuilder.append(myString.substring(cutPoint, c));
					listb.add(c - count);
					cutPoint = c + 3;
					count = count + 3;
				}
				if (myStringCharArray[c + 1] == '/'
						&& myStringCharArray[c + 2] == 'b') {
					strBuilder.append(myString.substring(cutPoint, c));
					listb.add(c - count);
					cutPoint = c + 4;
					count = count + 4;
				}
				if (myStringCharArray[c + 1] == 'i') {
					strBuilder.append(myString.substring(cutPoint, c));
					listi.add(c - count);
					cutPoint = c + 3;
					count = count + 3;
				}
				if (myStringCharArray[c + 1] == '/'
						&& myStringCharArray[c + 2] == 'i') {
					strBuilder.append(myString.substring(cutPoint, c));
					listi.add(c - count);
					cutPoint = c + 4;
					count = count + 4;
				}
			}

			if (myStringCharArray[c] == '[') {
				strBuilder.append(myString.substring(cutPoint, c));
				listPos.add(c - count);
				cutPoint = c + 1;
				count = count + 1;
			}

			if (myStringCharArray[c] == '|') {
				if (listPos.size() > 0) {
					for (int m = 0; m < listKeyAndValue.size(); m++) {
						String[] kv = listKeyAndValue.get(m).split("-");
						String s = myString
								.substring(listPos.get(0) + count, c);
						if (s.equals(kv[0])) {
							for (int d = -1; (d = myString.indexOf(s, d + 1)) != -1;) {
								strBuilder.append(myString.substring(cutPoint,
										c));
								cutPoint = c + kv[2].length() + 2;
								break;
							}
							count = count + kv[2].length() + 2;
							flag = 1;
						}
						if (flag == 1) {
							break;
						}
					}
					listPos.clear();
				} else {
					cutPoint = cutPoint + 2;
					count = count + 2;
				}
			}
		}

		strBuilder.append(myString.substring(cutPoint));
		uncompletedString = strBuilder.toString();
		myString = uncompletedString;

		return myString;
	}

	public void textEffect2(TextView textView, String text,
			final ArrayList<String> listkv, ArrayList<Integer> bold,
			ArrayList<Integer> italic) {
		textView.setMovementMethod(LinkMovementMethod.getInstance());
		textView.setText(text, BufferType.SPANNABLE);
		Spannable mySpannable3 = (Spannable) textView.getText();

		listPosKey = new ArrayList<String>();
		for (String item : listkv) {
			String[] pos = item.split("-");
			for (int d = -1; (d = text.indexOf(pos[0], d + 1)) != -1;) {
				int q = d + pos[0].length();
				listPosKey.add(d + "-" + q);
			}
		}

		for (String keyPosition : listPosKey) {
			String[] keyPos = keyPosition.split("-");

			final String test = text.substring(Integer.parseInt(keyPos[0]),
					Integer.parseInt(keyPos[1]));
			ClickableSpan myClickableSpan = new ClickableSpan() {
				@Override
				public void onClick(View widget) {
					for (String keyValue : listkv) {
						String[] kv = keyValue.split("-");

						if (test.equals(kv[0])) {
							String checkNumber = kv[2];
							Pattern pattern = Pattern.compile("\\d*");
							Matcher matcher = pattern.matcher(checkNumber);
							if(kv[1].equals("D")){
								OldDistrictManager manager = new OldDistrictManager(getApplicationContext());
								ArrayList<OldDistrict> list = new ArrayList<OldDistrict>();
								list.add(manager.searchByID(kv[2]));
								Intent i = new Intent(DetailPlaceActivity.this, DetailOldDistrictActivity.class);
								Bundle b = new Bundle();
								b.putSerializable("list", list);
								b.putString("id", manager.searchByID(kv[2]).getOldDistrictID());
								i.putExtras(b);
								startActivity(i);
							}
							else if(kv[1].equals("F")){
								FestivalManager manager = new FestivalManager(getApplicationContext());
								ArrayList<Festival> list = new ArrayList<Festival>();
								list.add(manager.searchByID(kv[2]));
								Intent i = new Intent(DetailPlaceActivity.this, DetailFestivalActivity.class);
								Bundle b = new Bundle();
								b.putSerializable("list", list);
								b.putString("id", manager.searchByID(kv[2]).getFestivalID());
								i.putExtras(b);
								startActivity(i);
							}
							else if(kv[1].equals("P")){
								PlaceManager manager = new PlaceManager(getApplicationContext());
								ArrayList<Place> list = new ArrayList<Place>();
								list.add(manager.searchByID(kv[2]));
								Intent i = new Intent(DetailPlaceActivity.this, DetailPlaceActivity.class);
								Bundle b = new Bundle();
								b.putSerializable("list", list);
								b.putString("id", manager.searchByID(kv[2]).getPlaceID());
								i.putExtras(b);
								startActivity(i);
							}
							else if(kv[1].equals("I")){
								IslandArticleManager manager = new IslandArticleManager(getApplicationContext());
								ArrayList<IslandArticle> list = new ArrayList<IslandArticle>();
								list.add(manager.searchByID(kv[2]));
								Intent i = new Intent(DetailPlaceActivity.this, DetailIslandArticleActivity.class);
								Bundle b = new Bundle();
								b.putSerializable("list", list);
								b.putString("id", manager.searchByID(kv[2]).getIslandArticleID());
								i.putExtras(b);
								startActivity(i);
							} else {
								if (duration.equals("0")) {
									Toast.makeText(getApplicationContext(),
											kv[2], Toast.LENGTH_SHORT).show();
								}
								if (duration.equals("1")) {
									Toast.makeText(getApplicationContext(),
											kv[2], Toast.LENGTH_LONG).show();
								}
							}
						}
					}
				}
			};

			mySpannable3.setSpan(myClickableSpan, Integer.parseInt(keyPos[0]),
					Integer.parseInt(keyPos[1]),
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}

		int k = 0;
		while (k < bold.size()) {
			mySpannable3.setSpan(new StyleSpan(Typeface.BOLD), bold.get(k),
					bold.get(k + 1), 0);
			k = k + 2;
		}
		int h = 0;
		while (h < italic.size()) {
			mySpannable3.setSpan(new StyleSpan(Typeface.ITALIC),
					italic.get(h), italic.get(h + 1), 0);
			h = h + 2;
		}
	}
	
	private void makeTag(TextView textView, String myTag) {

		listTag = new ArrayList<String>();
		StringTokenizer token = new StringTokenizer(myTag, ",");
		while (token.hasMoreTokens()) {
			listTag.add(token.nextToken().trim());
		}

		char[] myTagCharArray = myTag.toCharArray();
		int i = 0;
		listPosTag = new ArrayList<String>();
		for (int a = 0; a < myTagCharArray.length; a++) {
			if (myTagCharArray[a] == ',') {
				listPosTag.add(i + "-" + a);
				i = a + 2;
			}
		}
		listPosTag.add(i + "-" + (myTagCharArray.length));
		textView.setMovementMethod(LinkMovementMethod.getInstance());
		textView.setText(myTag, BufferType.SPANNABLE);
		Spannable mySpannable = (Spannable) textView.getText();

		for (String item : listPosTag) {
			String[] itemPosTag = item.split("-");
			final String t = myTag.substring(Integer.parseInt(itemPosTag[0]),
					Integer.parseInt(itemPosTag[1]));
			ClickableSpan myClickableSpan = new ClickableSpan() {
				@Override
				public void onClick(View widget) {
					for (String item2 : listTag) {

						if (item2.equals(t)) {
							Intent intent = new Intent(DetailPlaceActivity.this, SearchResultsActivity.class);
							intent.putExtra("tag", item2);
							startActivity(intent);
						}
					}
				}
			};
			mySpannable.setSpan(myClickableSpan,
					Integer.parseInt(itemPosTag[0]),
					Integer.parseInt(itemPosTag[1]),
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}

	}

}
